package com.bobo.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.bobo.dto.GoodsSalesDTO;
import com.bobo.entity.Orders;
import com.bobo.mapper.OrderMapper;
import com.bobo.mapper.UserMapper;
import com.bobo.service.ReportService;
import com.bobo.service.WorkspaceService;
import com.bobo.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计指定时间的营业额
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end的所有日期
        LocalDate current = begin;
        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);

        while (!current.equals(end)) {
            //计算指定日期后一天对应的日期
            current = current.plusDays(1);
            dateList.add(current);
        }

        //有groupby优化空间 已完成
        //查询begin到end中每天的营业额
        /*List<Double> turnoverList = new ArrayList<>();
        for(LocalDate date : dateList){
            //查询date对应的营业额，状态为已完成的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //select sum(amount) from orders where order_time>? and order_time<? and status=5
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null?0.0:turnover;
            turnoverList.add(turnover);
        }*/
        //计算整体时间范围

        Map<String, Object> map = new HashMap<>();
        map.put("begin",begin.atStartOfDay());
        map.put("end", end.plusDays(1).atStartOfDay());
        map.put("status", Orders.COMPLETED);
        //查询
        List<Map<String, Object>> dbData = orderMapper.sumDailyByRange(map);
        //创建日期金额映射（显形转换）
        Map<LocalDate, Double> resultMap = new HashMap<>();
        for (Map<String, Object> item : dbData) {
            LocalDate  date = ((LocalDateTime) item.get("date")).toLocalDate();
            Double amount = item.get("amount") != null ?
                    ((Number) item.get("amount")).doubleValue() :
                    0.0;
            resultMap.put(date, amount);
        }
        //生成结果列表
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            turnoverList.add(resultMap.getOrDefault(date, 0.0));
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 指定时间内用户数据统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUsertatistics(LocalDate begin, LocalDate end) {
        LocalDate current = begin;
        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);

        while (!current.equals(end)) {
            //计算指定日期后一天对应的日期
            current = current.plusDays(1);
            dateList.add(current);
        }

        //新用户数量 selsect count(id) from user where create_time<? and creat time>?
        List<Integer> newUserList = new ArrayList<>();

        //总用户数量 select count(id) from user where create_time<?
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("end",endTime);
            Integer totalUser = userMapper.countByMap(map);
            map.put("begin",beginTime);
            Integer newUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            newUserList.add(newUser);

        }
        //TODO 有一个去除for循环减少访问量思路
//         //能力有限优化不了
//        Map<String,Object> map = new HashMap<>();
//        map.put("end",end.plusDays(1).atStartOfDay());
//        //总数查询 传入map end time select sum(id) ,create_time  from user where create_time<? group by creat_time
//        List<Map<String, Object>> total = userMapper.countTotalByRange(map);
//        map.put("begin", begin.atStartOfDay());
//        //新增查询 select sum(id) from sum(id) ,create_time  from user where creat_time<? create_time>? order by create_time
//        List<Map<String, Object>> newUser = userMapper.countDaliyByRange(map);
//        Map<LocalDate, Integer> totalResultMap = new HashMap<>();
//        for(Map<String,Object> item : total){
//            java.sql.Date sqlDate = (java.sql.Date) item.get("date");
//            LocalDate  date = sqlDate.toLocalDate();  // 无需时区转换
//            Number totalUserNumber = (Number) item.getOrDefault("users",0);
//            Integer totalUsers = totalUserNumber.intValue();
//            totalResultMap.put(date,totalUsers);
//        }
//        for (LocalDate date : dateList) {
//            totalUserList.add(totalResultMap.getOrDefault(date,0));
//        }
//        Map<LocalDate, Integer> newResultMap = new HashMap<>();
//        for(Map<String,Object> item : newUser){
//            LocalDate  date = ((LocalDateTime) item.get("date")).toLocalDate();
//            Number newUsersNumber = (Number) item.get("users");
//            Integer newUsers = newUsersNumber.intValue();
//            newResultMap.put(date,newUsers);
//        }
//        for (LocalDate date : dateList) {
//            newUserList.add(newResultMap.getOrDefault(date,0));
//        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        LocalDate current = begin;
        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);

        while (!current.equals(end)) {
            //计算指定日期后一天对应的日期
            current = current.plusDays(1);
            dateList.add(current);
        }
        //TODO 有优化空间 去循环
        List<Integer> orderCountList = new ArrayList<>();//每天订单总数
        List<Integer> vallidCountList = new ArrayList<>();//每天有效订单数
        //遍历datelist查询有效订单数和订单数
        for (LocalDate date : dateList) {
            //查询订单总数每天 select count(id) from orders where order_time>? and order_time<e?
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            orderCountList.add(orderCount);
            //有效订单数每天 select count(id) from orders where order_time>? and order_time<? and status=5(COMPLETED)
            Integer vallidCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            vallidCountList.add(vallidCount);
        }
        //时间区间内订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内有效订单数
        Integer vallidOrderCount = vallidCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount!=0){
            orderCompletionRate =(double) vallidOrderCount / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(vallidCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(vallidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 根据条件统计订单数
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status) {
        Map map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);
        return orderMapper.countByMap(map);
    }

    /**
     * 获取销量前十
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //多表联查 orders orders_detail
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");



        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //查询数据库获取营业数据（最近30天）

        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));


        //写入excel文件，POI
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //基于模板创建一个新的文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //填充数据--时间
            XSSFSheet sheet = excel.getSheet("sheet1");
            //表格填充
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);
            //获得第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            //第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //明细数据填充

            //TODO 可优化
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //第一次遍历第八行   获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //通过输出流下载到客户端
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
